<?php

namespace App\Http\Controllers\Wechat;

use App\Model\KeyWord;
use App\Model\Reply;
use App\Model\WxReply;
use App\Server\WechatServer;
use Houdunwang\WeChat\WeChat;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ApiController extends Controller
{
    public function __construct(WechatServer $wechatServer)
    {
        $wechatServer->link();
    }
    public function handler(){
        $replys=Reply::find(1);
        $instance = WeChat::instance('message');
        if ($instance->isSubscribeEvent())
        {
          return  $instance->text($replys->welcome);
        }
        if ($instance->isTextMsg()){
            $message=$instance->getMessage();
            $keyword=KeyWord::where('keyword',$message->Content)->first();
            if ($keyword){
                $reply=WxReply::where('rule_id',$keyword['rule_id'])->first();
                if ($reply['type']==text){
                    $reply_hui=array_random(json_decode($reply['content'],true));
                    return $instance->text($reply_hui['content']);
                }else if($reply['type']=='image'){
                    $nes=json_decode($reply['content'],true);
                    return $instance->neews($nes);
                }
            }
        }
        $instance=WeChat::instance('button');
        if ($instance->isClickEvent()){
            $message=$instance->getMessage();
            $keyword=KeyWord::where('rule_id',$keyword['keyword'])->value('content');
            $huifu=array_random(json_decode($reply,true));
            return WeChat::instance('message')->text($huifu['content']);


        }
    }
}
